package com.study.mybatis.executor;

import com.study.mybatis.common.CommonCons;
import com.study.mybatis.datasource.UnPoolDatasource;
import com.study.mybatis.executor.statement.StatementHandler;
import com.study.mybatis.mapping.MappedStatement;
import com.study.mybatis.session.Configuration;
import com.study.mybatis.session.ResultHandler;


import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;

/**
 * @author yuantongqin
 * 2021/7/31
 **/
public class SimpleExecutor extends BaseExecutor {

    private Configuration configuration;

    public SimpleExecutor(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> doQuery(MappedStatement ms, Object parameter) {
        try {
            return doQuery(ms, parameter, null);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public <E> List<E> doQuery(MappedStatement ms, Object parameter, ResultHandler resultHandler) throws SQLException {
        Statement stmt = null;
        try {
            Configuration configuration = ms.getConfiguration();
            StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, resultHandler);
            stmt = prepareStatement(handler,parameter);
            return handler.query(stmt, resultHandler);
        } finally {
            closeStatement(stmt);
        }
    }


    @Override
    public void doUpdate(MappedStatement ms, Object parameter) {

    }

    @Override
    public Configuration getConfig() {
        return this.configuration;
    }


    private Statement prepareStatement(StatementHandler handler,Object parameter) throws SQLException {
        Statement stmt;
        Connection connection = getConnection();
        stmt = handler.prepare(connection, 3000);
        handler.parameterize(stmt,parameter);
        return stmt;
    }

    public Connection getConnection(){
        Properties config = this.configuration.getConfig();
        String driver = config.getProperty(CommonCons.driver);
        String url = config.getProperty(CommonCons.url);
        String username = config.getProperty(CommonCons.username);
        String password = config.getProperty(CommonCons.password);
        UnPoolDatasource unPoolDatasource = new UnPoolDatasource(driver, url, username, password);
        Connection connection = unPoolDatasource.doGetConnection();

        return connection;
    }
}
